<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>copyToClipboard</title>
</head>

<body>
    <div id="test">被复制的文本</div>
    <button type="button" id="copyBtn">点我复制</button>
    <script>
        const copyToClipboard = str => {
            const el = document.createElement('textarea');
            el.value = str;
            el.setAttribute('readonly', '');
            el.style.position = 'absolute';
            el.style.position = '-9999px';
            document.body.appendChild(el);
            const selected =
                document.getSelection().rangeCount > 0
                    ? document.getSelection().getRangeAt(0)
                    : false;
            el.select();
            document.execCommand();
            document.body.removeChild(el);
            if (selected) {
                document.getSelection().removeAllRanges();
                document.getSelection().addRange(selected);
            }
        };
        const btn = document.getElementById('copyBtn');
        const text = document.getElementById('test');
        btn.onclick = function () {
            copyToClipboard(text.textContent);
            alert('复制成功');
        }
    </script>
</body>

</html>